package com.xyy.ec.qualification.service;

import com.alibaba.fastjson.JSON;
import com.xyy.ec.qualification.enums.TaskEnum;
import com.xyy.ec.qualification.exception.ServiceException;
import com.xyy.ec.qualification.pojo.PopRestDto;
import com.xyy.ec.qualification.pojo.SellerDataConfig;
import com.xyy.ec.qualification.task.TaskHandler;
import com.xyy.ec.qualification.utils.http.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.sql.Blob;
import java.util.*;

import static com.xyy.ec.qualification.utils.MergedUrl.mergeUrl;

/**
 * 数据库二进制流，且数据库版本是SQL Server2005，且字段类型是image类型用这个
 */
@Slf4j
@Service("blob")
public class BlobDataSyncServiceHandel extends DataSyncServiceHandel implements TaskHandler {

    @Override
    public void handleDrugReport(TaskEnum taskEnum) {
        syncErpDataToPop(taskEnum);
    }

    @Override
    public void handleFirstBattalionQualification(TaskEnum taskEnum) {
        syncErpDataToPop(taskEnum);
    }


    @Override
    public List<Map<String, Object>> fileConvert2Url(TaskEnum taskEnum, List<Map<String, Object>> serverResultList) {
        List<Map<String, Object>> newServerResultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(serverResultList)) {
            return newServerResultList;
        }
        //请求头必须设置，否则报错
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;charset=UTF-8");

        Map<String, String> params = new HashMap<>();
        params.put("appKey", SellerDataConfig.appKey);

        log.info("{}数据转化开始，待转化数据数量={}", taskEnum.getTaskName(),serverResultList.size());

        for (Map<String, Object> map : serverResultList) {
            try {
                Object o = map.get(taskEnum.getValueField());
                if (Objects.isNull(o) ) {
                    log.error("{}地址格式异常", taskEnum.getTaskName());
                    continue;
                }
                Blob blob = (Blob) o;
                byte[] bytes = blob.getBytes(1, (int) blob.length());

                log.info("当前任务 {} 数据转化中,erpCode = {}",taskEnum.getTaskName() ,map.get(taskEnum.getQueryField()));

                //文件名称必须带后缀，否则服务器识别不到文件类型
                String url = RedirectUtil.doPostByFrom(getUploadUrl(), headers, params, UUID.randomUUID().toString()+".jpg", bytes);
                PopRestDto restDto = JSON.parseObject(url, PopRestDto.class);
                if(Objects.isNull(restDto) || ! restDto.getStatus() || StringUtils.isBlank(restDto.getData())){
                    throw new ServiceException("文件上报异常");
                }

                Map<String, Object> newMap = new HashMap<>();
                newMap.putAll(map);
                newMap.put(taskEnum.getValueField(), restDto.getData());
                newServerResultList.add(newMap);
            } catch (Exception e) {
                log.info("{}数据转化异常,date={}", taskEnum.getTaskName(),map.get(taskEnum.getQueryField()));
            }
        }
        return mergeUrl(newServerResultList,taskEnum.getTaskId());
    }
}
